package com.gopay.common.util.xml.utils;

import org.apache.commons.beanutils.PropertyUtils;

public class XmlBeansUtils {
	
	/**
	 * 
	 * @param path
	 * @return
	 * @throws CheckMessageException 
	 * @throws Exception
	 */
	public static Object createObjInstance(String path) throws Exception{
		Assert0.notEmpty4String(path, "The path must not be empty.");
		try {
			return Class.forName(path).newInstance();
		} catch (Exception e) {
			throw new Exception("init object error, path: " + path, e);
		}
	}
	
	/**
	 * 获得该元素对应的vo对象的属性的值
	 * 
	 * @param data
	 * @param field
	 * @return
	 * @throws Exception
	 */
	public static String getPropertyString(Object data, String name, String defaultValue)
			throws Exception {
		Object value = getPropertyObject(data, name);
		return value == null ? defaultValue : value.toString()
				.trim();
	}
	
	/**
	 * 
	 * @param data
	 * @param name
	 * @param type
	 * @param value
	 * @throws Exception
	 */
	public static void setPropertyObject(Object data, String name, String type, Object value)
			throws Exception {
		try {
			Converter converter = BeanConverterUtil.getInstance().getConverter(type);
			value = converter.convert(value);
			PropertyUtils.setProperty(data, name, value);
		} catch (Throwable e) {
			throw new RuntimeException("setProperty error, className: " + data.getClass().getName() + "|name: " + name + "|type: " + type + "|value: " + value, e);
		}
	}

	/**
	 * 获得该元素对应的vo对象的属性的值
	 * 
	 * @param data
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static Object getPropertyObject(Object data, String name){
		try {
			return PropertyUtils.getProperty(data, name);
		} catch (Exception e) {
			throw new RuntimeException("getProperty error, className: " + data.getClass().getName() + "|name: " + name, e);
		}
	}
}
